var http = require('http');
var util = require('util');//固定格式
var ip = '127.0.0.1';
var fs = require('fs');
var url = require('url');
var dk = 80;
var siteName = "留言板";
var server = http.createServer(function (request, response) {

	response.statusCode = 200;
	response.setHeader('Content-Type','text/html')
	var ext = request.url.substr(request.url.lastIndexOf('.')+1);
	var exts = {
		'html':'text/html',
		'css':'text/css',
		'js':'text/javascript',
		'jpg':'image/jpeg',
		'png':'image/png'
	}
	if (exts[ext] == null) {
		exts[ext] ="text/plain"
	}
	
	response.setHeader('Content-Type',exts[ext])
	var data = '404';
	var p = url.parse(request.url,true);
	//console.log(p);
	if (p.pathname =='/index.html') {
	try{
		data = fs.readFileSync('.'+request.url,'utf8');
		data = data.replace(/%title/g,siteName);
		item = fs.readFileSync('data.json','utf8');
		item = JSON.parse(item);
		//console.log(item);

		var s = "";
		for (var i = 0; i < item.length; i++) {
			s+='<div class="item">';
			s+='<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>';
			s+='<p>'+item[i].message+'</p>';
			s+='</div>';
	}
		data = data.replace(/%main/g,s);
	}catch(e){
		//console.log(e),打印错误
	}
	}else if (p.pathname == '/from.html') {
		data = fs.readFileSync('.'+request.url,'utf8');
	}else if (p.pathname == '/addmessage.html'){
		author = p.query.author;
		message = p.query.message;
		item = JSON.parse(fs.readFileSync('data.json','utf8'));//本段调用以前的留言数据
		item.push({
			author:author,
			message:message,
			time:new Date()
		})
		item = JSON.stringify(item)
		fs.writeFileSync('data.json',item)
		data = "提交成功"
		response.writeHead(302,{
			'Location':'/index.html'
		});

	}/*else if (p.pathname == '/delmessage')*/
	response.write(data);
	response.end();
})
server.listen(dk);

// 终端打印如下信息
console.log('Server running at http://%s:%s/',ip,dk);